﻿using System.Data;

namespace Citi.GocAttributes.Domain.Utils
{
    public static class Context
    {
        public static string ConnectionString;
        private static GocAttributesEntities instance;
        private static readonly object Padlock = new object();

        /// <summary>
        /// Instancia estática do Contexto de entidades
        /// </summary>
        public static GocAttributesEntities Instance
        {
            get
            {
                lock (Padlock)
                {
                    if (instance != null) return instance;

                    instance = ConnectionString != null
                        ? new GocAttributesEntities(ConnectionString)
                        : new GocAttributesEntities();

                    return instance;
                }
            }
        }

        public static void SaveChanges()
        {
            try
            {
                Instance.SaveChanges();
            }
            catch (UpdateException)
            {
                throw; 
            }
            catch
            {
                ClearContext();
            }
        }

        public static void ClearAddedInContext()
        {
            var objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Added);

            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void ClearContext()
        {
            ClearAddedInContext();
            
            var objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
            
            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
            
            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void Delete(object entity)
        {
            Instance.DeleteObject(entity);
            SaveChanges();
        }
    }
}
